//
//  YFDontaiManageVC.m
//  project
//
//  Created by yefei on 2019/4/15.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFDontaiManageVC.h"
#import "YFDongtaiCell.h"
#import "YFDongtaiModel.h"

@interface YFDontaiManageVC () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSArray<YFDongtaiRecordModel *> *dongtais;
@property (nonatomic, strong) UIButton *editButton;
@property (nonatomic, strong) NSMutableArray<NSString *> *selectedArray;
@property (nonatomic, copy) NSString *albumIds;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewConstraintTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewConstraintBottom;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *dongtaiNumersLabel;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *deleteButtonConstraintBottom;


@end

@implementation YFDontaiManageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"动态管理";
    [self setupViews];
    [self loadData];
}

- (void)setupViews {
    [self setupNavigationRightButton];
    [self setupDongtaiCollectionView];
    [self.contentView rounded:(UIRectCornerAllCorners) radius:10];
}

- (void)loadData {
    self.dongtais = [NSArray array];
    self.selectedArray = [NSMutableArray arrayWithCapacity:1];
    [self.collectionView.mj_header beginRefreshing];
}

- (void)setupNavigationRightButton {
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 0, 60, 44);
    button.titleLabel.font = [UIFont fontWithName:PingFangSC_Medium size:16];
    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateHighlighted)];
    [button setTitle:@"编辑" forState:(UIControlStateNormal)];
    self.navigaitonBar.rightCustomView = button;
    @weakify(self)
    [[button rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self manageDongtaiButtonClicked:x];
    }];
    self.editButton = button;
}

- (void)manageDongtaiButtonClicked:(UIButton *)button {
    button.selected = !button.selected;
    NSString *title = button.selected ? @"取消" : @"管理";
    [button setTitle:title forState:(UIControlStateNormal)];
    
    if (!button.selected) {
        [self.selectedArray removeAllObjects];
    }
    [self.collectionView reloadData];
    
    [self.collectionView reloadData];
    
    [self deletonButtonIsShow:button.selected];
    
    LKLog(@"编辑选中的id数组：%@", self.selectedArray);
}

- (void)setupDongtaiCollectionView {
    // 注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"YFDongtaiCell" bundle:nil] forCellWithReuseIdentifier:@"YFDongtaiCell"];
    
    @weakify(self)
    [self.collectionView refresh:^{
        @strongify(self)
        self.page = 1;
        [self loadDongtaisWithPage:self.page];
    }];
    [self.collectionView loadMore:^{
        @strongify(self)
        self.page += 1;
        [self loadDongtaisWithPage:self.page];
    }];
    self.collectionView.emptyView = self.tipEmptyView;
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dongtais.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YFDongtaiCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YFDongtaiCell" forIndexPath:indexPath];
    if (_dongtais && _dongtais.count > 0 && indexPath.row < _dongtais.count) {
        cell.model = _dongtais[indexPath.row];
    }
    cell.isEditting = _editButton.selected;
    @weakify(self)
    cell.editDeleteAction = ^(BOOL isSelected, NSString * _Nonnull albumIds) {
        @strongify(self)
        [self editting:isSelected albumId:albumIds];
    };
    return  cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *albumId = self.dongtais[indexPath.row].albumId;
    LKLog(@"当前AlbumId:%@", albumId);
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 12, 10, 12);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((SCREEN_WIDTH - 44 - 24) / 3, (SCREEN_WIDTH - 44 - 24) / 3 * 1.1);
}

#pragma mark - Update Contrstranit
- (void)updateViewConstraints {
    [super updateViewConstraints];
    self.contentViewConstraintTop.constant = NAVIGATION_BAR_HEIGHT + 12;
    self.contentViewConstraintBottom.constant = STATUS_BAR_HEIGHT == 44 ? SAFE_AREA_HEIGHT : 12;
}

#pragma mark - 网络请求
- (void)loadDongtaisWithPage:(NSInteger)page {
    
    BOOL isRefresh = self.collectionView.mj_header.state == MJRefreshStateRefreshing;
    NSString *postString = [Api stringByAppendingString:MyDongtaiApi];
    NSDictionary *params = @{
                             @"userId": [HJUserManager getUserModel].userId,
                             @"pageCurrent": @(page)
                             };
    @weakify(self)
    [HJHttpTool post:postString params:params success:^(HJResponeds *result) {
        @strongify(self)
         LKLog(@"动态管理：%@", result);
        
        // 获取数据失败
        if (!result.isSuccess) {
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            if (self.dongtais && self.dongtais.count) {
                // 列表有数据 提示网络信息
                [YFHud showError:result.resultDesc];
            } else {
                // 列表没有数据
                // 2. 隐藏 mj_footer
                self.collectionView.mj_footer.hidden = YES;
            }
            return ;
        }
        // 获取成功
        // 刷新tableView
        NSDictionary *dataDict = result.data;
        YFDongtaiModel *model = [YFDongtaiModel yy_modelWithDictionary:dataDict];
        if (isRefresh) {
            self.dongtais = model.records;
        } else {
            self.dongtais = [self.dongtais arrayByAddingObjectsFromArray:model.records];
        }
        self.dongtaiNumersLabel.text = [NSString stringWithFormat:@"(%zd)", self.dongtais.count];
        [self.collectionView reloadData];
        
        // 停止刷新
        if (isRefresh) {
            [self.collectionView.mj_header endRefreshing];
        }
        
        // 是否到底
        BOOL isNoMoreData = model.pages == self.page;
        
        // 到底了
        if (isNoMoreData) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            // 没有到底
            [self.collectionView.mj_footer endRefreshing];
        }
        
        // 如果刷新有数据，则显示mj_footer
        if (self.dongtais && self.dongtais.count) {
            self.collectionView.mj_footer.hidden = NO;
        } else {
            self.collectionView.mj_footer.hidden = YES;
        }
    } failure:^(id result) {
        @strongify(self)
        LKLog(@"%@", result);
        
        // 停止刷新
        if (isRefresh) {
            [self.collectionView.mj_header endRefreshing];
        }
        [self.collectionView.mj_footer endRefreshing];
        if (self.dongtais && self.dongtais.count) {
            // 列表有数据 提示网络信息
            [YFHud showError:result];
        } else {
            // 列表没有数
            // 2. 隐藏 mj_footer
            self.collectionView.mj_footer.hidden = YES;
        }
    }];
}

- (void)deleteDogntai:(NSString *)ablumIds {
    
    NSString *postString = [Api stringByAppendingString:DeleteDongtaiApi];
    NSDictionary *params = @{
                             @"ablumIds": ablumIds,
                             @"userId": [HJUserManager getUserModel].userId,
                             };
    [YFHud showProgress:@"删除中"];
    @weakify(self)
    [HJHttpTool post:postString params:params success:^(HJResponeds *result) {
        @strongify(self)
        if (result.isSuccess) {
            [YFHud showSuccess:@"删除成功"];
            [self reloadDataAfterDelete];
        } else {
            [YFHud showError:result.resultDesc];
        }
    } failure:^(id result) {
        [YFHud showError:result];
    }];
    
}

#pragma mark - 对编辑进行操作
- (void)editting:(BOOL)isSelected albumId:(NSString *)albumId {
    
    BOOL isRepeation = NO;
    
    // 查重
    for (NSString *album_id in self.selectedArray) {
        if ([albumId isEqualToString:album_id]) {
            isRepeation = YES;
        }
    }
   
    LKLog(@"是否重复%d", isRepeation);
    
    // 添加或删除
    if (isSelected) {
        if (!isRepeation) [self.selectedArray addObject:albumId];
    } else {
        if (isRepeation) [self.selectedArray removeObject:albumId];
    }
    
    // 格式化成字符串
    __block NSString *albumIds = @"";
    @weakify(self)
    [self.selectedArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @strongify(self)
        
        if (self.selectedArray.count == 1) {
            albumIds = obj;
        } else if (idx == self.selectedArray.count - 1) {
            albumIds = [albumIds stringByAppendingString:obj];
        } else {
            albumIds = [[albumIds stringByAppendingString:obj] stringByAppendingString:@","];
        }
    }];
    self.albumIds = albumIds;
    
    LKLog(@"编辑：选中的 albumIds：%@", self.albumIds);
    
    self.deleteButton.enabled = self.selectedArray.count != 0;
}

#pragma mark - 对数据源进行操作 删除删除的动态
- (void)reloadDataAfterDelete {
    
    NSMutableArray <YFDongtaiRecordModel *> *dongtaiCopy = [NSMutableArray arrayWithArray:self.dongtais];
    for (NSString *albumId in self.selectedArray) {
        for (YFDongtaiRecordModel *model in self.dongtais) {
            if ([albumId isEqualToString:model.albumId]) {
                [dongtaiCopy removeObject:model];
            }
        }
    }
    self.dongtaiNumersLabel.text = [NSString stringWithFormat:@"(%zd)", self.dongtais.count];
    self.dongtais = [dongtaiCopy mutableCopy];
    [self.collectionView reloadData];
    
    [self.selectedArray removeAllObjects];
    self.albumIds = @"";
}

#pragma mark - 删除按钮的动画显示
- (void)deletonButtonIsShow:(BOOL)isShow {
    if (isShow) {
        self.deleteButtonConstraintBottom.constant = 0;
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 55, 0);
    } else {
        self.deleteButtonConstraintBottom.constant = - (SAFE_AREA_HEIGHT + 55);
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (IBAction)delecteClicked:(id)sender {
    
    if (self.selectedArray.count == 0) {
        [YFHud showMessage:@"您未选中动态"];
        return;
    }
    
    [self deleteDogntai:self.albumIds];
}

@end


